import { Button, Spin, Tree } from "antd";
import { useAuthMenu } from "../hooks/useAuthMenu";
import AuthMenu from "./AuthMenu";
import { useCallback, useEffect, useState } from "react";
import { Menu } from "@/types/system/menu";
import PermissionBtn from "@/components/PermissionBtn";
import { queryMenuTree } from "@/api/system/menu";
import { queryRoleMenuIds } from "@/api/system/role";
import { PlusOutlined } from "@ant-design/icons";

interface Props {
  roleId: string;
  roleName: string;
}
export default function ViewMenuAuth(props: Props) {
  const [loading, setLoading] = useState(false);
  const [menuIds, setMenuIds] = useState<Array<string>>([]);
  const [menuTree, setMenuTree] = useState<Menu[]>([]);
  const { isModalOpen, close, openOptionDialog, roleId, roleName } =
    useAuthMenu();
  /**
   * 回显接口
   * @param data
   */
  const getSelected = useCallback(async () => {
    if (!props.roleId) false;
    const res = await queryRoleMenuIds(props.roleId);
    if (res.code === 200) {
      const list = res.data || [];
      setMenuIds(list.map((item) => item.menuId));
    }
  }, [props.roleId]);
  /**
   * 获取菜单树
   */
  const getMenuList = async () => {
    setLoading(true);
    const res = await queryMenuTree();
    setLoading(false);
    if (res.code === 200) {
      const list = res.data || [];
      setMenuTree(list);
    }
  };
  /**
   * 初始化
   */
  const initForm = useCallback(async () => {
    if (props.roleId) {
      await getSelected();
    }
    await getMenuList();
  }, [getSelected, props.roleId]);

  useEffect(() => {
    initForm();
  }, [initForm]);
  return (
    <div>
      <div className="flex flex--e">
        <PermissionBtn code="role.authMenu">
          <Button
            type="primary"
            size="middle"
            icon={<PlusOutlined />}
            onClick={() => {
              openOptionDialog(props.roleId, props.roleName);
            }}
          >
            分配菜单
          </Button>
        </PermissionBtn>
      </div>
      <Spin spinning={loading}>
        <Tree
          checkable
          onCheck={(ids) => {
            setMenuIds(ids as string[]);
          }}
          fieldNames={{ title: "menuName", key: "id", children: "children" }}
          checkedKeys={menuIds}
          treeData={menuTree}
          checkStrictly={true}
        />
      </Spin>
      {isModalOpen && (
        <AuthMenu
          isModalOpen={isModalOpen}
          close={close}
          roleId={roleId}
          roleName={roleName}
          change={()=>{
            initForm()
          }}
        />
      )}
    </div>
  );
}
